import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    list: [],
    inputVal: '',
    maxId: 5,
    btnStatus: 'all'
  },
  mutations: {
    // 获取所有的数据存储到list当中
    listInfo(state, list) {
      state.list = list
    },

    // 当输入框数据改变时
    setInputValue(state, value) {
      state.inputVal = value
    },

    // 点击按钮添加新项
    addItemHandle(state) {
      const obj = {
        id: state.maxId,
        info: state.inputVal.trim(),
        done: false
      }
      state.list.push(obj)
      state.inputVal = ''
      state.maxId++
    },

    // 点击删除按钮时
    removeItemHandle(state, id) {
      const index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
    },

    //  当切换多选框状态时
    getCheckbox(state, params) {
      const index = state.list.findIndex(item => item.id === params.id)
      if (index !== -1) {
        state.list[index].done = params.done
      }
    },

    //  当切换按钮的状态时
    btnStatusChange(state, status) {
      state.btnStatus = status
    }
  },
  actions: {
    // 发送请求获取数据
    getList(context) {
      axios.get('/list.json').then(data => {
        context.commit('listInfo', data.data)
      })
    }
  },
  getters: {
    // 获取剩余未选中的列表数据的条数
    getNum(state) {
      return state.list.filter(item => item.done === false).length
    },
    //  当切换按钮的状态时 对应选中状态的复选框项显示
    btnStatusShow(state) {
      switch (state.btnStatus) {
        case 'all':
          return state.list
        case 'udone':
          return state.list.filter(item => item.done === false)
        case 'done':
          return state.list.filter(item => item.done === true)
        default:
          return state.list
      }
    }
  }
})
